package service

import (
	"com.cyt.yunpay/app/dao"
	"com.cyt.yunpay/app/model"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/util/grand"
	"github.com/gogf/gf/database/gdb"
)

var Member = new(memberService)

type memberService struct{}

// 用户注册
func (s *memberService) CreateMember(r *model.Member) (int, error) {
	r.Uid = s.generateId();
	if _, err := dao.Member.Save(r); err != nil {
		return r.Uid, err
	}
	return r.Uid, nil
}

// 保存手机号
func (s *memberService) SaveMobile(id int, mobile string) error {
	info := g.Map{
		"mobile":  mobile,
		"is_bind_mobile": 1,
	}
	if _, err := dao.Member.Where("uid", id).Data(info).Update(); err != nil {
		return err
	}
	return nil
}

// 保存实名认证状态
func (s *memberService) SaveRealNameAuth(uid int) error {
	info := g.Map{
		"is_real_auth":  1,
	}
	if _, err := dao.Member.Where("uid", uid).Data(info).Update(); err != nil {
		return err
	}
	return nil
}

//保存实名认证状态
func (s *memberService) SaveRealNameAuthTx(uid int, tx *gdb.TX) (error) {
	data := g.Map{
		"is_real_auth":  1,
	}
	_, err := g.Table("member").TX(tx).Where("uid", uid).Data(data).Update()
	if err != nil {
		return err
	}
	return nil
}

// 保存身份信息
func (s *memberService) SaveIdentityInfoTx(r *model.MemberIdentityInfo, tx *gdb.TX) (error) {
	if _, err := g.Table("member_identity_info").TX(tx).Save(r); err != nil {
		return err
	}
	return nil
}

// 保存身份信息
func (s *memberService) SaveIdentityInfo(r *model.MemberIdentityInfo) (error) {
	if _, err := dao.MemberIdentityInfo.Save(r); err != nil {
		return err
	}
	return nil
}

// 根据用户名查询
func (s *memberService) GetUserByUsername(username string) (*model.Member, error) {
	data, err := dao.Member.FindOne("username=?", username)
	if err != nil {
		return nil, err
	}
	//Context.SetMember(ctx, &model.ContextMember{
	//	Id:       data.Id,
	//	UserName: data.UserName,
	//})
	return data, nil
}

func (s *memberService) GetUserByUsernamePassword(serviceReq *model.ServiceLoginReq) map[string]interface{} {
	if serviceReq.Username == "admin" && serviceReq.Password == "admin" {
		return g.Map{
			"id":       1,
			"username": "admin",
		}
	}
	return nil
}

func (s *memberService) generateId() int {
	return grand.N(100000, 999999)
}